﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Zjh.PackSerializer.Utils;

namespace Zjh.PackSerializer.Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Model m = new Model()
            {
                Id = 1,
                Name = "Model Name",
                Server = "Server host",
                ServerPort = 9090,
                CreateTime = DateTime.Now,
                IsUsed = true,
                Address = new Address
                {
                    Id = 10,
                    Line1 = "Line1",
                    Line2 = "Address Line2"
                },
                Files = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0xA },
                FileArray = new int[] { 0x10, 0x11, 0x12, 0x13 }
            };

            IList array = new int[5];
            Console.WriteLine(array.GetType().GetElementType().FullName);

            IList list = (IList)(object)new List<int>();
            Console.WriteLine(array.GetType().GetElementType().FullName);

            IPackSerializer serializer = PackSerializerFactory.DefaultSerializer;

            var a = serializer.Serialize((uint)0x1024);
            BinaryUtil.ConsolePrintFormat(a);
            Console.WriteLine(serializer.Deserialize<uint>(a).ToString("X4"));
            var b = serializer.Serialize("Hello world");
            BinaryUtil.ConsolePrintFormat(b);
            Console.WriteLine(serializer.Deserialize<string>(b));

            var buffer = serializer.Serialize(m);
            BinaryUtil.ConsolePrintFormat(buffer);

            var obj = serializer.Deserialize<Model>(buffer);

            var loop = 10000;
            Timeuse(() =>
            {
                for (int i = 0; i < loop; i++)
                {
                    buffer = serializer.Serialize(m);
                }
            }, time =>
            {
                Console.WriteLine("Serialize use time({0}): {1}ms, {2}ms/c", loop, time, time / loop);
            });
            Timeuse(() =>
            {
                for (int i = 0; i < loop; i++)
                {
                    obj = serializer.Deserialize<Model>(buffer);
                }
            }, time =>
            {
                Console.WriteLine("Deserialize use time({0}): {1}ms, {2}ms/c", loop, time, time / loop);
            });

            BinaryUtil.ConsolePrintFormat(serializer.Serialize(obj));

            Console.ReadLine();
        }

        private static void Timeuse(Action act, Action<decimal> after)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            act?.Invoke();
            watch.Stop();
            after?.Invoke(watch.ElapsedMilliseconds);
        }
    }
}